package com.logic.landseaserver.common.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.logic.landseaserver.common.enums.BillTypeEnum;

/**
 * string tools
 *
 * @author junny
 * @version C02 2016年5月12日
 */
public class StringTools
{
    /** 分隔符 **/
    public static final String SEPRATOR_1 = "/";
    
    /** 分隔符 **/
    public static final String SEPRATOR_2 = "\\";
    
    final static Map<Integer, String> zoneNum = new HashMap<Integer, String>();
    
    static
    {
        zoneNum.put(11, "北京");
        zoneNum.put(12, "天津");
        zoneNum.put(13, "河北");
        zoneNum.put(14, "山西");
        zoneNum.put(15, "内蒙古");
        zoneNum.put(21, "辽宁");
        zoneNum.put(22, "吉林");
        zoneNum.put(23, "黑龙江");
        zoneNum.put(31, "上海");
        zoneNum.put(32, "江苏");
        zoneNum.put(33, "浙江");
        zoneNum.put(34, "安徽");
        zoneNum.put(35, "福建");
        zoneNum.put(36, "江西");
        zoneNum.put(37, "山东");
        zoneNum.put(41, "河南");
        zoneNum.put(42, "湖北");
        zoneNum.put(43, "湖南");
        zoneNum.put(44, "广东");
        zoneNum.put(45, "广西");
        zoneNum.put(46, "海南");
        zoneNum.put(50, "重庆");
        zoneNum.put(51, "四川");
        zoneNum.put(52, "贵州");
        zoneNum.put(53, "云南");
        zoneNum.put(54, "西藏");
        zoneNum.put(61, "陕西");
        zoneNum.put(62, "甘肃");
        zoneNum.put(63, "青海");
        zoneNum.put(64, "宁夏");
        zoneNum.put(65, "新疆");
        zoneNum.put(71, "台湾");
        zoneNum.put(81, "香港");
        zoneNum.put(82, "澳门");
        zoneNum.put(91, "外国");
    }
    
    final static int[] PARITYBIT = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
    
    final static int[] POWER_LIST = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    
    /**
     * 身份证验证
     *
     * @return 是否有效 null和"" 都是false
     * @params 号码内容
     */
    public static boolean isIDCard(String certNo)
    {
        if (certNo == null || (certNo.length() != 15 && certNo.length() != 18))
            return false;
        final char[] cs = certNo.toUpperCase().toCharArray();
        // 校验位数
        int power = 0;
        for (int i = 0; i < cs.length; i++)
        {
            if (i == cs.length - 1 && cs[i] == 'X')
                break;// 最后一位可以 是X或x
            if (cs[i] < '0' || cs[i] > '9')
                return false;
            if (i < cs.length - 1)
            {
                power += (cs[i] - '0') * POWER_LIST[i];
            }
        }
        
        // 校验区位码
        if (!zoneNum.containsKey(Integer.valueOf(certNo.substring(0, 2))))
        {
            return false;
        }
        
        // 校验年份
        String year = certNo.length() == 15 ? getIdcardCalendar() + certNo.substring(6, 8) : certNo.substring(6, 10);
        
        final int iyear = Integer.parseInt(year);
        if (iyear < 1900 || iyear > Calendar.getInstance().get(Calendar.YEAR))
            return false;// 1900年的PASS，超过今年的PASS
            
        // 校验月份
        String month = certNo.length() == 15 ? certNo.substring(8, 10) : certNo.substring(10, 12);
        final int imonth = Integer.parseInt(month);
        if (imonth < 1 || imonth > 12)
        {
            return false;
        }
        
        // 校验天数
        String day = certNo.length() == 15 ? certNo.substring(10, 12) : certNo.substring(12, 14);
        final int iday = Integer.parseInt(day);
        if (iday < 1 || iday > 31)
            return false;
        
        // 校验"校验码"
        if (certNo.length() == 15)
            return true;
        return cs[cs.length - 1] == PARITYBIT[power % 11];
    }
    
    private static int getIdcardCalendar()
    {
        GregorianCalendar curDay = new GregorianCalendar();
        int curYear = curDay.get(Calendar.YEAR);
        int year2bit = Integer.parseInt(String.valueOf(curYear).substring(2));
        return year2bit;
    }
    
    public static List<Integer> formatString(String ids)
    {
        List<Integer> fileIds = new ArrayList<>();
        if (StringUtils.isEmpty(ids))
        {
            fileIds = null;
        }
        else
        {
            String[] fIds = ids.split(",");
            for (String str : fIds)
            {
                fileIds.add(Integer.parseInt(str));
            }
        }
        return fileIds;
    }
    
    public static String changeIdNo(String idNo)
    {
        if (StringUtils.isEmpty(idNo) || idNo.length() < 12)
        {
            return idNo;
        }
        String idNoPrefix = idNo.substring(4, 12);
        String starChar = idNo.replace(idNoPrefix, "********");
        return starChar;
    }
    
    public static String buildString(String msg, String[] listString)
    {
        if (listString.length > 0)
        {
            for (int i = 0; i < listString.length; i++)
            {
                String str = listString[i];
                msg = msg.replace("[%" + i + "]", str);
            }
            return msg;
        }
        else
        {
            return msg;
        }
        
    }
    public static String buildBillName(String msg, String str)
    {
        if (!StringUtils.isEmpty(str)){
            msg = msg.replace("[%0]", str);
            return msg;
        }else{
            return msg;
        }
    }
    public static boolean isPhone(String number)
    {
        boolean flag = false;
        try
        {
            Pattern p = Pattern.compile("^[0-9]{11}$");
            Matcher m = p.matcher(number);
            flag = m.matches();
        }
        catch (Exception e)
        {
            flag = false;
        }
        return flag;
    }
    
    public static boolean containsKey(String[] list, String seachKay)
    {
        boolean handleFlag = false;
        if (list != null)
        {
            for (String keys : list)
            {
                if (keys.equals(seachKay))
                {
                    handleFlag = true;
                }
            }
        }
        return handleFlag;
    }
    
    /**
     * 
     * [简要描述]：拼接路径或url</br>
     * [详细描述]：在最后拼接</br>
     * [作者]：Aaron(2017-06-27)</br>
     *
     * @param source 源path
     * @param destAddPath 待拼接的字符串
     * @return 拼接后的结果字符串
     *
     */
    public static String splitJointPath(String source, String destAddPath)
    {
        if (org.apache.commons.lang3.StringUtils.isEmpty(source))
        {
            return destAddPath;
        }
        if (org.apache.commons.lang3.StringUtils.isEmpty(destAddPath))
        {
            return source;
        }
        
        // 获取系统的路径分割符/或\
        String systemSeparator = System.getProperty("file.separator");
        
        // 判断source最后是否有分隔符
        if (source.endsWith(SEPRATOR_1) || source.endsWith(SEPRATOR_2))
        {
            source = source.substring(0, source.length() - 1);
        }
        
        if (destAddPath.startsWith(SEPRATOR_1) || destAddPath.startsWith(SEPRATOR_2))
        {
            destAddPath = destAddPath.substring(1, destAddPath.length());
        }
        
        source = source + systemSeparator + destAddPath;
        
        return source;
    }

    public static String getFileName(String path){
        String fileName = "";
        try {
            fileName= path.substring(path.lastIndexOf("/")+1);
         //   fileName = fileNm.split("\\.")[0];
        }catch (Exception e){
            return fileName;
        }
        return fileName;
    }

    public static String getEmunName(String code){
        String emName="";
        if(code.equals("COMMON")){
            return "通用";
        }
        for(BillTypeEnum em : BillTypeEnum.values()){
            if(StringUtils.equals(code, em.getCode())){
                emName= em.getName();
            }
        }
        return emName;
    }

    public static String getEmunCode(String name){
        String emCode="";
        for(BillTypeEnum em : BillTypeEnum.values()){
            if(StringUtils.equals(name, em.getName())){
                emCode= em.getCode();
            }
        }
        return emCode;
    }
    
    /**
     * 
     * [简要描述]：获取字符串</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-07-24)</br>
     *
     * @param object
     * @return
     *
     */
    public static String getString(Object object)
    {
        return null == object ? "" : object.toString();
    }
    
    public static String getStr(String s)
    {
        return null == s ? "" : s;
    }
    
    /**
     * 
     * [简要描述]：将数字list拼装成sql</br>
     * [详细描述]：例如 and preKey in (1,2,3)</br>
     * [作者]：Aaron(2017-10-17)</br>
     *
     * @param preKey
     * @param list
     * @return
     *
     */
    public static String packageAndInSqlbyListInt(String preKey, List<Integer> list)
    {
        if (CollectionUtils.isEmpty(list) || org.apache.commons.lang3.StringUtils.isEmpty(preKey))
        {
            return "";
        }       
        
        StringBuilder stringBuilder = new StringBuilder();        
        stringBuilder.append(preKey + " in (");        
        int size = list.size();       
        for (int i = 0 ; i < size; i ++)
        {
            stringBuilder.append(list.get(i));
            
            if (i != size - 1)
            {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append(")");        
        return stringBuilder.toString();
    }
    
    /**
     * 
     * [简要描述]：将字符串list拼装成sql</br>
     * [详细描述]：例如 and preKey in ('s1','s2','s3')</br>
     * [作者]：Aaron(2017-10-17)</br>
     *
     * @param preKey
     * @param list
     * @return
     *
     */
    public static String packageAndInSqlbyListStr(String preKey, List<String> list)
    {
        if (CollectionUtils.isEmpty(list) || org.apache.commons.lang3.StringUtils.isEmpty(preKey))
        {
            return "";
        }       
        
        StringBuilder stringBuilder = new StringBuilder();        
        stringBuilder.append(preKey + " in (");        
        int size = list.size();       
        for (int i = 0 ; i < size; i ++)
        {
            stringBuilder.append("'" + list.get(i) + "'");
            
            if (i != size - 1)
            {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append(")");        
        return stringBuilder.toString();
    }






    /**
     * 复制对象属性
     * @param from
     * @param to
     * @param excludsArray 排除属性列表
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static void copyPropertiesExclude(Object from, Object to, String[] excludsArray) throws Exception {
        List<String> excludesList = null;
        if(excludsArray != null && excludsArray.length > 0) {
            excludesList = Arrays.asList(excludsArray); //构造列表对象
        }
        Method[] fromMethods = from.getClass().getDeclaredMethods();
        Method[] toMethods = to.getClass().getDeclaredMethods();
        Method fromMethod = null, toMethod = null;
        String fromMethodName = null, toMethodName = null;
        for (int i = 0; i < fromMethods.length; i++) {
            fromMethod = fromMethods[i];
            fromMethodName = fromMethod.getName();
            if (!fromMethodName.contains("get"))
                continue;
            //排除列表检测
            if(excludesList != null && excludesList.contains(fromMethodName.substring(3).toLowerCase())) {
                continue;
            }
            toMethodName = "set" + fromMethodName.substring(3);
            toMethod = findMethodByName(toMethods, toMethodName);
            if (toMethod == null)
                continue;
            Object value = fromMethod.invoke(from, new Object[0]);
            if(value == null)
                continue;
            //集合类判空处理
            if(value instanceof Collection) {
                Collection newValue = (Collection)value;
                if(newValue.size() <= 0)
                    continue;
            }
            toMethod.invoke(to, new Object[] {value});
        }
    }

    /**
     * 从方法数组中获取指定名称的方法
     *
     * @param methods
     * @param name
     * @return
     */
    public static Method findMethodByName(Method[] methods, String name) {
        for (int j = 0; j < methods.length; j++) {
            if (methods[j].getName().equals(name))
                return methods[j];
        }
        return null;
    }

    /**
     * 
     * [简要描述]：产生一个UUID</br>
     * [详细描述]：</br>
     * [作者]：Aaron(2017-10-23)</br>
     *
     * @return
     *
     */
    public static String generateUuid()
    {
        return UUID.randomUUID().toString();
    }
}
